﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kgb.Model.Models;
using Kgb.Service.Repository.Interface;
using System.Runtime.Caching;

namespace Kgb.Service.Repository
{
    public class LobbyRepository : ILobbyRepository
    {
        private List<Lobby> _lobbys;
        private int _nextId;

        public LobbyRepository()
        {
            if (MemoryCache.Default["lobbys"] == null)
            {
                _lobbys = new List<Lobby>();
                MemoryCache.Default.Add(new CacheItem("lobbys", _lobbys), new CacheItemPolicy() { AbsoluteExpiration = new DateTime(9999, 12, 31) });
            }
            else
            {
                _lobbys = (List<Lobby>)MemoryCache.Default["lobbys"];
            }

            if (_lobbys.Any())
            {
                _nextId = _lobbys.Max(c=>c.Id) + 1;
            }
            else
            {
                _nextId = 1;
                this.Add(new Lobby() { Name = "Entrada", State = "Vazia" });
            }
        }

        public IQueryable<Lobby> GetAll()
        {
            return _lobbys.AsQueryable();
        }

        public Lobby Get(int id)
        {
            return _lobbys.Find(c => c.Id == id);
        }

        public Lobby Add(Lobby lobby)
        {
            lobby.Id = _nextId++;
            _lobbys.Add(lobby);
            return lobby;
        }

        public void Remove(int id)
        {
            Lobby lobby = _lobbys.Find(c => c.Id == id);
            if (lobby != null)
                _lobbys.Remove(lobby);
        }

        public bool Update(Lobby lobby)
        {
            int index = _lobbys.FindIndex(c => c.Id == lobby.Id);
            if (index == -1)
            {
                return false;
            }
            _lobbys.RemoveAt(index);
            _lobbys.Add(lobby);   
            return true;
        }
    }
}